#!/usr/bin/env bash

# Copyright 2016 The Fuchsia Authors
# Copyright (c) 2008 Travis Geiselbrecht
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

function HELP {
    echo "help:"
    echo "-a                  : add intel hda sound"
    echo "-b                  : a virtio block device"
    echo "-n                  : a virtio network device"
    echo "-g                  : with graphics"
    echo "-k                  : use KVM"
    echo "-6                  : x86-64"
    echo "-m <memory in MB>"
    echo "-s <number of cpus>"
    echo "-h for help"
    echo "all arguments after -- are passed to qemu directly"
    exit 1
}

DO_AUDIO=0
DO_BLOCK=0
DO_NET=0
DO_64BIT=0
DO_GRAPHICS=0
DO_KVM=0
MEMSIZE=512
SMP=1
SUDO=""
MAKE_VARS=""

while getopts 6abngkm:s:h FLAG; do
    case $FLAG in
        a) DO_AUDIO=1;;
        b) DO_BLOCK=1;;
        n) DO_NET=1;;
        6) DO_64BIT=1;;
        g) DO_GRAPHICS=1;;
        k) DO_KVM=1;;
        m) MEMSIZE=$OPTARG;;
        s) SMP=$OPTARG;;
        h) HELP;;
        \?)
            echo unrecognized option
            HELP
    esac
done

shift $((OPTIND-1))

if [ $DO_64BIT == 1 ]; then
    QEMU="qemu-system-x86_64"
    PROJECT="pc-x86-64-test"
else
    QEMU="qemu-system-i386"
    PROJECT="pc-x86-test"
fi

AUDIO_ARGS=" -soundhw hda"
BLOCK_ARGS=" -drive if=virtio,file=blk.bin,id=blk,format=raw"
NET_ARGS=" -netdev type=user,hostname=qemu,id=net0 -device virtio-net-pci,netdev=net0"

ARGS=" -m $MEMSIZE -smp $SMP -machine q35 -kernel build-${PROJECT}/zircon.bin"

if [ $DO_AUDIO == 1 ]; then
    ARGS+=$AUDIO_ARGS
    export QEMU_AUDIO_DRV=none
fi
if [ $DO_BLOCK == 1 ]; then
    ARGS+=$BLOCK_ARGS
fi
if [ $DO_NET == 1 ]; then
    ARGS+=$NET_ARGS
fi
if [ $DO_GRAPHICS == 0 ]; then
    ARGS+=" -nographic"
else
    ARGS+=" -serial stdio"
fi
if [ $DO_KVM != 0 ]; then
    ARGS+=" -enable-kvm -cpu host"
fi

make $MAKE_VARS $PROJECT -j4 &&
echo $SUDO $QEMU $ARGS $@ &&
$SUDO $QEMU $ARGS $@

